<template>
  <div class="seckill-good">
    <Navigation></Navigation>
    <div class="good-block">
      <div class="good-img">
        <!-- 这里的v-if判断是为了防止el-image的图片渲染失败，这个是element-ui的问题 -->
        <!-- 如果不添加v-if，图片会时而加载成功，时而加载失败，并且控制台日志会报404错误 -->
        <el-image style="width: 400px; height: 350px" :src="goodInfo.good_img" :preview-src-list="preview" title="点击预览"
          :lazy="true" v-if="this.goodInfo.good_img !== undefined">
        </el-image>
      </div>

      <div class="good-info">
        <div class="good-title">产品名: {{ goodInfo.good_title }}</div>

        <div class="good-seckill">
          <div class="seckill-price">
            <span style="text-decoration: line-through">原价: {{ goodInfo.price }}元</span>
            <span style="font-weight: bold; margin-left: 2%">￥秒杀价: {{ goodInfo.seckill_price }}元</span>
          </div>
          <div class="seckill-end-time">
            <el-statistic v-if="new Date(this.goodInfo.start_time) > new Date()" :value="Date.now() + (new Date(this.goodInfo.start_time) - Date.now())
              " time-indices @finish="finishCount()">
              <template slot="prefix">距离活动结束开始还有：</template>
            </el-statistic>

            <el-statistic :value="Date.now() + (new Date(this.goodInfo.end_time) - Date.now())
              " time-indices @finish="finishCount()" v-else>
              <template slot="prefix">距离活动结束时间还有：</template>
            </el-statistic>
          </div>
        </div>

        <div class="good-total">产品总量: {{ goodInfo.total }}件</div>

        <div class="good-surplus">产品剩余量: {{ goodInfo.remain }}件</div>

        <div class="start-time">
          开始时间:
          {{ goodInfo.start_time | dateFormat("yyyy-mm-dd hh:mm:ss") }}
        </div>

        <div class="end-time">
          结束时间: {{ goodInfo.end_time | dateFormat("yyyy-mm-dd hh:mm:ss") }}
        </div>

        <div class="seckill-btn">
          <el-button type="danger" disabled v-show="new Date(this.goodInfo.start_time) > new Date()">活动未开始</el-button>
          <el-button type="danger" disabled v-show="new Date(this.goodInfo.end_time) < new Date()">活动已结束</el-button>
          <el-button v-if="!isSeckilling" type="primary" v-show="new Date(this.goodInfo.start_time) <= new Date() &&
            new Date(this.goodInfo.end_time) >= new Date()
            " @click="genToken()">立即抢购</el-button>
          <el-button type="primary" v-else loading="true">抢购中</el-button>
        </div>

        <div class="go-back">
          <router-link to="/goodList">返回</router-link>
        </div>
      </div>

      <div class="good-introduction">
        <h2 style="text-align: center">产品介绍</h2>
        <div class="good-intro-content">
          {{ goodInfo.good_desc }}
        </div>
      </div>
    </div>

    <el-dialog :append-to-body="true" :close-on-click-modal="false" :close-on-press-escape="false" title="请选择收货地址"
      :visible.sync="submitOrderDialog" width="57%" show-close="false" center>
      <AddrList mode="choose" @handleChooseAddr="handleChooseAddr" @submitOrder="handleSubmitOrder"></AddrList>
    </el-dialog>
  </div>
</template>

<script>
import { getGoodInfo, seckill, generateToken } from "@/api/good";
import { mapState } from "vuex";
import { submitOrder } from '@/api/order'
import AddrList from '@/components/addrList'


export default {
  name: "SeckillGood",
  components: {
    AddrList
  },
  data() {
    return {
      goodInfo: {},
      preview: [""],
      time: null,
      isSeckilling: false,
      submitOrderDialog: false,

      chooseId: 0,
      orderId: ''
    };
  },
  computed: {
    ...mapState({
      userId: (state) => state.login.userId,
    }),
  },
  created() {
    this.getInfo(this.$route.params.goodId);
  },
  methods: {
    getInfo(goodId) {
      getGoodInfo(goodId).then((res) => {
        this.goodInfo = res.data;
        this.preview[0] = this.goodInfo.good_img;
      });
    },

    genToken() {
      this.isSeckilling = true
      let uid = this.userId
      let goodId = this.goodInfo.good_id

      generateToken(uid, goodId).then((res) => {
        this.seckillGood(uid, goodId, res.data)
      }).catch(() => {
        this.isSeckilling = false
      })
    },

    seckillGood(uid, goodId, token) {
      seckill(uid, goodId, token).then((res) => {
        if (this.goodInfo.is_delivery === '1') {
          this.$message.success('抢购成功，请选择您的收货地址')
          // 打开收货地址选择对话框
          this.submitOrderDialog = true
          this.orderId = res.msg
        } else {
          this.$message.success('抢购成功，正在为您跳转至支付页面')
          this.$router.push(/payOrder/ + res.msg);
        }
      }).catch(() => {
        this.isSeckilling = false
      })
    },

    finishCount() {
      this.getInfo(this.$route.params.goodId);
    },

    handleChooseAddr(addrId) {
      this.chooseId = addrId
      this.$message.success('已选择收货地址，点击提交订单按钮即可提交。')
    },

    handleSubmitOrder() {
      if (!this.chooseId || this.chooseId === 0) {
        this.$message.error('请选择您的收货地址')
        return false
      }

      submitOrder(this.chooseId, this.orderId).then((res) => {
        if (res.code === 200) {
          this.$message.success('订单提交成功，正在为您跳转至支付页面')
          this.$router.push(/payOrder/ + this.orderId);
        }
      })
    }
  },
};
</script>

<style>
.seckill-good {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url("../assets/register.png");
  width: 100%;
  background-size: cover;
  min-height: 100vh;
  font-size: 18px;
}

.good-block {
  padding-top: 5%;
  padding-left: 20%;
  padding-right: 20%;
}

.good-img {
  display: block;
  float: left;
}

.good-info {
  display: block;
  float: right;
  height: 350px;
  width: 450px;
}

.good-title {
  background: #dbdbdb;
  font-size: 30px;
  font-weight: 800;
  padding: 5px;
  padding-left: 3%;
}

.good-seckill {
  background: #dbdbdb;
  margin-top: 20px;
  line-height: 40px;
  height: 70px;
  font-size: 20px;
  padding-left: 3%;
}

.seckill-end-time {
  font-weight: bold;
  font-size: 20px;
  float: left;
}

.el-statistic .con {
  color: red;
}

.good-total,
.good-surplus,
.start-time,
.end-time {
  margin-top: 15px;
  margin-left: 3%;
}

.seckill-btn button {
  width: 450px;
  font-size: 25px;
  letter-spacing: 10px;
  margin-top: 20px;
}

.go-back a {
  text-decoration: none;
  color: #774c4c;
  font-size: 20px;
  font-weight: 800;
  display: block;
  float: right;
}

.go-back a:hover {
  color: #c02323;
}

.good-introduction {
  position: absolute;
  width: 60%;
  height: 30%;
  top: 55%;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgb(236, 240, 247);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-top: 100px;
}

.good-intro-content {
  font-size: 17px;
  text-indent: 34px;
  padding-left: 17px;
  padding-right: 17px;
}
</style>
